package com.ruoyi.app.business.project;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.app.config.util.UserUtil;
import com.ruoyi.app.domain.project.sudden.ProjectSudden;
import com.ruoyi.app.domain.project.sudden.ProjectSuddenSave;
import com.ruoyi.common.core.enums.YesNoEnum;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.PageUtils;
import com.ruoyi.common.core.web.page.CommonPageInfo;
import com.ruoyi.service.project.entity.ProjectEntity;
import com.ruoyi.service.project.entity.ProjectSuddenEntity;
import com.ruoyi.service.project.query.ProjectSuddenBaseQuery;
import com.ruoyi.service.project.service.ProjectService;
import com.ruoyi.service.project.service.ProjectSuddenService;
import com.ruoyi.service.user.entity.UserEntity;
import com.ruoyi.service.user.service.UserService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 作用：项目相关业务
 * </p>
 *
 * @author Zane
 * @since 2025-10-10 2:19
 */
@Slf4j
@Component
public class ProjectSuddenBusiness {

  @Resource
  private ProjectService projectService;
  @Resource
  private ProjectSuddenService projectSuddenService;
  @Resource
  private UserService userService;

  public CommonPageInfo<ProjectSudden> list(ProjectSuddenBaseQuery suddenQuery) {
    CommonPageInfo<ProjectSuddenEntity> pageInfo = PageUtils.startPage(suddenQuery.getPageNum(),
        suddenQuery.getPageSize());
    pageInfo.initData(
        Optional.ofNullable(projectSuddenService.listByProjectId(suddenQuery.getProjectId()))
            .orElseGet(ArrayList::new));
    final ProjectEntity projectInfo = CommonUtils.requireNotNull(
        projectService.getById(suddenQuery.getProjectId()), "项目ID错误");
    final CommonPageInfo<ProjectSudden> result = pageInfo.convert(this::projectSuddenConvert);
    //补充人员姓名
    if (CollUtil.isNotEmpty(result.getList())) {
      final Map<Long, Long> userIdMap = new HashMap<>();
      result.getList().forEach(v -> {
        userIdMap.put(v.getCreateBy(), v.getCreateBy());
        userIdMap.put(v.getUpdateBy(), v.getUpdateBy());
      });
      final List<Long> userList = new ArrayList<>(userIdMap.keySet());
      final Map<Long, UserEntity> userMap = userService.userMapByIds(userList);
      result.getList().forEach(v -> {
        v.setCreateName(userMap.get(v.getCreateBy()).getName())
            .setUpdateName(userMap.get(v.getUpdateBy()).getName())
            .setProjectName(projectInfo.getProjectName())
        ;
      });
    }
    return result;
  }

  public ProjectSudden detail(Long id) {
    final ProjectSuddenEntity suddenEntity = CommonUtils.requireNotNull(
        projectSuddenService.getById(id),
        "异常ID错误");
    ProjectSudden projectSudden = projectSuddenConvert(suddenEntity);
    final Map<Long, Long> userIdMap = new HashMap<Long, Long>() {{
      put(projectSudden.getCreateBy(), projectSudden.getCreateBy());
      put(projectSudden.getUpdateBy(), projectSudden.getUpdateBy());
    }};
    final List<Long> userList = new ArrayList<>(userIdMap.keySet());
    final Map<Long, UserEntity> userMap = userService.userMapByIds(userList);
    final ProjectEntity projectInfo = CommonUtils.requireNotNull(
        projectService.getById(projectSudden.getProjectId()), "项目ID错误");
    projectSudden.setCreateName(userMap.get(projectSudden.getCreateBy()).getName())
        .setUpdateName(userMap.get(projectSudden.getUpdateBy()).getName())
        .setProjectName(projectInfo.getProjectName())
    ;
    return projectSudden;
  }

  public void save(ProjectSuddenSave suddenSave) {
    //判断项目ID
    final ProjectEntity project = CommonUtils.requireNotNull(
        projectService.getById(suddenSave.getProjectId()), "项目ID不存在");
    projectSuddenService.saveOrUpdate(
        toEntity(suddenSave).setProjectCreator(project.getCreateBy()));
  }

  public void delete(Long id) {
    final ProjectSuddenEntity entity = CommonUtils.requireNotNull(
        projectSuddenService.getById(id), "异常ID不存在");
    entity.setUpdateBy(UserUtil.getUserId())
        .setUpdateTime(LocalDateTime.now())
        .setDeleteFlag(YesNoEnum.YES.getCode());
    projectSuddenService.updateById(entity);
  }

  private ProjectSudden projectSuddenConvert(ProjectSuddenEntity projectSuddenEntity) {
    return new ProjectSudden()
        .setId(projectSuddenEntity.getId())
        .setProjectId(projectSuddenEntity.getProjectId())
        .setInfo(projectSuddenEntity.getInfo())
        .setReason(projectSuddenEntity.getReason())
        .setCreateBy(projectSuddenEntity.getCreateBy())
        .setCreateTime(projectSuddenEntity.getCreateTime())
        .setUpdateBy(projectSuddenEntity.getUpdateBy())
        .setUpdateTime(projectSuddenEntity.getUpdateTime());
  }

  private ProjectSuddenEntity toEntity(ProjectSuddenSave sudden) {
    final Long userId = UserUtil.getUserId();
    final LocalDateTime now = LocalDateTime.now();
    final ProjectSuddenEntity newEntity = new ProjectSuddenEntity()
        .setId(sudden.getId())
        .setProjectId(sudden.getProjectId())
        .setInfo(sudden.getInfo())
        .setReason(sudden.getReason())
        .setCreateBy(userId)
        .setCreateTime(now)
        .setUpdateBy(userId)
        .setUpdateTime(now);
    if (Objects.nonNull(sudden.getId())) {
      final ProjectSuddenEntity oldEntity = CommonUtils.requireNotNull(
          projectSuddenService.getById(sudden.getId()), "异常ID不存在");
      newEntity.setCreateBy(oldEntity.getCreateBy())
          .setCreateTime(oldEntity.getCreateTime());
    }
    return newEntity;
  }

}
